﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using SD.BUS;
using SD.Common;
using SD.Entities;
using SD.IBUS;
using System.Data.SqlClient;

namespace SD.UI
{
    public partial class EditOrganization : BasePage
    {

        private static string ASCENDING = " ASC";
        private static string DESCENDING = " DESC";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {

                    if (Session["fString"] == null) // no filter string param
                    {
                        Session.Add("fString", "");
                    }
                    if (Session["includeInactive"] == null) // no include inactive param
                    {
                        Session.Add("includeInactive", false);
                    }

                    ShowDetail1();
                    ShowDetail2();
                    ShowDetail3();
                    LoadData(Session["fString"].ToString(), Convert.ToBoolean(Session["includeInactive"]));
                }
                catch (SqlException)
                {
                    ShowMessage(ERROR_SQL_EXCEPTION);
                }
                catch (Exception)
                {
                    Response.Redirect("CommomError.aspx");
                }

                ShowDetail5();
            }

        }

        protected void chkExpOfInterest_CheckedChanged(object sender, EventArgs e)
        {
            if (chkExpOfInterest.Checked)
            {
                tabsDetail3.Visible = true;
                TabContainer1.ActiveTabIndex = 2;

                // Bind data to textbox, when checkbox has autopostback envent, 
                // values in textbox are not miss or change. 
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {
                tabsDetail3.Visible = false;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("ShowOrganizationList.aspx");
        }

        protected void btnInActive_Click(object sender, EventArgs e)
        {
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            try
            {
                iOrganizationBIZ.SetActive(Request.QueryString["orgId"].ToString(), false);
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "ShowOrganizationList.aspx");
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
                return;
            }
            catch (Exception)
            {
                Response.Redirect("CommomError.aspx");
            }
        }

        private Boolean IsDuplicateName(String orgName)
        {
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            List<Organization> lstOrg = new List<Organization>();
            try
            {
                lstOrg = iOrganizationBIZ.GetOrgByName(tbxOrgName.Text.Trim());
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            if ((lstOrg.Count > 0) && !lstOrg[0].OrgId.Equals(Request.Params["orgId"]))
            {
                // Load values to enable textbox
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;

                return true;
            }
            else
            {
                return false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();

            // Check Organization name has existed in database
            if (IsDuplicateName(tbxOrgName.Text.Trim()))
            {
                ShowMessage(ERROR_DUPLICATE_NAME);
            }
            else
            {
                Organization organization = new Organization();
                // Set Detail 1
                organization.OrgId = Request.QueryString["orgId"].ToString();
                organization.Name = tbxOrgName.Text;
                organization.ShortDescription = tbxOrgShortDes.Text;
                organization.IsPreferred = chkPreOrganization.Checked;
                organization.IsExpressionOfInterest = chkExpOfInterest.Checked;
                organization.FullDescription = tbxOrgFullDescription.Text;
                organization.Phone = tbxPhoneNumber.Text;
                organization.Fax = tbxFax.Text;
                organization.Email = tbxEmail.Text;
                organization.Web = tbxWebAddress.Text;
                organization.Charity = tbxCharityNumber.Text;
                organization.Company = tbxCompanyNumber.Text;
                organization.IsExpressionOfInterest = chkExpOfInterest.Checked;

                Address address = new Address();
                address.AddressId = String.IsNullOrEmpty(txtAddressID.Value) ? null : txtAddressID.Value;
                organization.Address = address;

                ReferenceData referenceData = new ReferenceData();
                referenceData.RefId = String.IsNullOrEmpty(txtBussinessID.Value) ? null : txtBussinessID.Value;
                organization.BusinessType = referenceData;

                Contact contact = new Contact();
                contact.ContactId = String.IsNullOrEmpty(txtContactID.Value) ? null : txtContactID.Value;
                organization.Contact = contact;

                organization.IsActive = true;

                try
                {
                    // Set detail 2
                    organization.Details2 = GetDetail2();

                    // Set detail 3
                    organization.Programmes = new List<Programme>();
                    organization.Services = new List<Service>();

                    // Set detail 4
                    organization.SupportingMaterials = new List<SupportingMaterial>();

                    // Set detail 5
                    organization.Directorates = new List<Directorate>();

                    // Update to database
                    iOrganizationBIZ.Update(organization);
                    ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "ShowOrganizationList.aspx");
                }
                catch (SqlException)
                {
                    ShowMessage(ERROR_SQL_EXCEPTION);
                }
                catch (Exception)
                {
                    Response.Redirect("CommomError.aspx");
                }
            }
        }

        protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
        {
            Session["indexTab"] = TabContainer1.ActiveTabIndex;
        }

        #region Load Data
        /// <summary>
        /// Load tab detail 1
        /// </summary>
        private void ShowDetail1()
        {
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            Organization organization = null;
            try
            {
                organization = iOrganizationBIZ.GetById(Request.QueryString["orgId"]);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (organization == null) // error occur
            {
                return;
            }

            // Set value for detail 1 tab
            tbxOrgName.Text = organization.Name;

            tbxOrgShortDes.Text = organization.ShortDescription;

            tbxLeadContact.Text = organization.Contact == null ? "N/A" : organization.Contact.Surname;

            if (organization.Address != null) // set address if it is not null
            {
                // set address details
                tbxAddressLine1.Text = organization.Address.Line1;
                tbxAddressLine2.Text = organization.Address.Line2;
                tbxAddressLine3.Text = organization.Address.Line3;

                tbxCityTown.Text = organization.Address.Town == null ? "" : organization.Address.Town.Name;
                tbxCounty.Text = organization.Address.County == null ? "" : organization.Address.County.Name;
                tbxNationCountry.Text = organization.Address.Country == null ? "" : organization.Address.Country.Name;
                tbxPostcode.Text = organization.Address.PostCode;

                // set hidden field
                txtAddressID.Value = organization.Address.AddressId;
            }

            tbxOrgFullDescription.Text = organization.FullDescription;

            tbxSICCode.Text = organization.BusinessType == null ? "N/A" : organization.BusinessType.RefCode;

            tbxTypeOfBussiness.Text = organization.BusinessType == null ? "N/A" : organization.BusinessType.RefValue;

            tbxOrgShortDes.Text = organization.FullDescription;

            tbxPhoneNumber.Text = organization.Phone;

            tbxWebAddress.Text = organization.Web;

            tbxFax.Text = organization.Fax;

            tbxEmail.Text = organization.Email;

            tbxCharityNumber.Text = organization.Charity;

            tbxCompanyNumber.Text = organization.Company;

            chkExpOfInterest.Checked = organization.IsExpressionOfInterest;

            chkPreOrganization.Checked = organization.IsPreferred;

            txtBussinessID.Value = organization.BusinessType == null ? null : organization.BusinessType.RefId;
            txtContactID.Value = organization.Contact == null ? null : organization.Contact.ContactId;

            // enable tab detail 3
            tabsDetail3.Visible = chkExpOfInterest.Checked;
        }

        //---------------------------------------------------------------------
        //---------------------------Show Detail 2------------------------------
        /// <summary>
        /// Load detail 2 
        /// </summary>
        private void ShowDetail2()
        {
            IOrgDetail2BIZ orgDetail2BIZ = new OrgDetail2BIZ();
            String orgID = Request.Params["orgId"];
            List<String> lstOrgDetail2 = new List<String>();

            try
            {
                lstOrgDetail2 = orgDetail2BIZ.GetByOrganization(orgID);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // =========================================
            IReferenceDataBIZ iRef = new ReferenceDataBIZ();
            DataTable dtOS, dtSDC, dtSBaC, dtSBeC, dtSPCC, dtSEC, dtA;
            dtOS = iRef.ListReferenceDataByRefcode("Organisation Specicalism");
            dtSDC = iRef.ListReferenceDataByRefcode("Service Disabilities Capabilities");
            dtSBaC = iRef.ListReferenceDataByRefcode("Service Barriers Capabilites");
            dtSBeC = iRef.ListReferenceDataByRefcode("Service Benenfits Capabilites");
            dtSPCC = iRef.ListReferenceDataByRefcode("Service Personal Circumstances Capabilites");
            dtSEC = iRef.ListReferenceDataByRefcode("Service Ethnicity Capabilites");
            dtA = iRef.ListReferenceDataByRefcode("Accreditation");

            // ============== data binding ==============

            // bind Specicalism
            ckbOrgSpecicalism.DataSource = dtOS;
            ckbOrgSpecicalism.DataValueField = "RefID";
            ckbOrgSpecicalism.DataTextField = "RefValue";
            ckbOrgSpecicalism.DataBind();
            CheckDetail(ckbOrgSpecicalism.Items, lstOrgDetail2);

            // bind Services Disablities Capabilities
            listSerDisCapabilities.DataSource = dtSDC;
            listSerDisCapabilities.DataValueField = "RefID";
            listSerDisCapabilities.DataTextField = "RefValue";
            listSerDisCapabilities.DataBind();
            CheckDetail(listSerDisCapabilities.Items, lstOrgDetail2);

            // Services Barrires Capablities
            listSerBarCapablities.DataSource = dtSBaC;
            listSerBarCapablities.DataValueField = "RefID";
            listSerBarCapablities.DataTextField = "RefValue";
            listSerBarCapablities.DataBind();
            CheckDetail(listSerBarCapablities.Items, lstOrgDetail2);

            // bind Services Benefits Capablities
            listSerBeneCapablities.DataSource = dtSBeC;
            listSerBeneCapablities.DataValueField = "RefID";
            listSerBeneCapablities.DataTextField = "RefValue";
            listSerBeneCapablities.DataBind();
            CheckDetail(listSerBeneCapablities.Items, lstOrgDetail2);

            // bind Services Peronal Circumstanc
            clistSerPerCirCapabilities.DataSource = dtSPCC;
            clistSerPerCirCapabilities.DataValueField = "RefID";
            clistSerPerCirCapabilities.DataTextField = "RefValue";
            clistSerPerCirCapabilities.DataBind();
            CheckDetail(clistSerPerCirCapabilities.Items, lstOrgDetail2);

            // bind Services Ethnicity Capablities
            listSerEthCapablities.DataSource = dtSEC;
            listSerEthCapablities.DataValueField = "RefID";
            listSerEthCapablities.DataTextField = "RefValue";
            listSerEthCapablities.DataBind();
            CheckDetail(listSerEthCapablities.Items, lstOrgDetail2);

            // bind Accreditation
            listAccreditation.DataSource = dtA;
            listAccreditation.DataValueField = "RefID";
            listAccreditation.DataTextField = "RefValue";
            listAccreditation.DataBind();
            CheckDetail(listAccreditation.Items, lstOrgDetail2);
        }

        //---------------------------------------------------------------------
        //-----------------------------Show Detail 3----------------------------
        private void ShowDetail3()
        {
            IProgrammeBIZ iproBIZ = new ProgrammeBIZ();
            IServiceBIZ iserBIZ = new ServiceBIZ();
            IProgrammeBIZ iProgarmmeBIZ = new ProgrammeBIZ();
            IServiceBIZ iServiceBIZ = new ServiceBIZ();

            DataTable dtPro, dtSer;
            List<String> lstProgrammeIDs = new List<String>();
            List<String> lstServiceIDs = new List<String>();

            try
            {
                dtPro = iproBIZ.GetAll(false);
                dtSer = iserBIZ.GetAll(false);
                //MISSING LOAD PROGRAMMES & SERVICES

                // Load Programmes
                clistEOIProgrammes.DataSource = dtPro;
                clistEOIProgrammes.DataTextField = "Name";
                clistEOIProgrammes.DataBind();
                CheckDetail(clistEOIProgrammes.Items, lstProgrammeIDs);

                // Load Services
                clistEOIServices.DataSource = dtSer;
                clistEOIServices.DataTextField = "Name";
                clistEOIServices.DataBind();
                CheckDetail(clistEOIProgrammes.Items, lstProgrammeIDs);
                CheckDetail(clistEOIServices.Items, lstServiceIDs);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region Suppoting Methods

        /// <summary>
        /// Set detail 2 for updated organization
        /// </summary>
        private List<ReferenceData> GetDetail2()
        {
            List<ReferenceData> lstDetail2 = new List<ReferenceData>();
            IReferenceDataBIZ refDate2BIZ = new ReferenceDataBIZ();

            try
            {
                // traverse over Org Specicalism
                foreach (ListItem item in ckbOrgSpecicalism.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // traverse over SerDisCapabilities
                foreach (ListItem item in listSerDisCapabilities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // Services Barrires Capablities
                foreach (ListItem item in listSerBarCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Benefits Capablities
                foreach (ListItem item in listSerBeneCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Peronal Circumstanc
                foreach (ListItem item in clistSerPerCirCapabilities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Ethnicity Capablities
                foreach (ListItem item in listSerEthCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Accreditation
                foreach (ListItem item in listAccreditation.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lstDetail2;
        }

        /// <summary>
        /// Auto check the detail item of the organization while loading
        /// </summary>
        /// <param name="lstItems">List of loaded items</param>
        /// <param name="details">ID list of the refdata</param>
        private void CheckDetail(ListItemCollection lstItems, List<String> lstDetails)
        {
            foreach (ListItem item in lstItems)
            {
                if (IsExistInList(item.Value, lstDetails))
                {
                    item.Selected = true;
                }
            }
        }

        /// <summary>
        /// Check whether a string is exist in a list
        /// </summary>
        /// <param name="strChecked">Checked string</param>
        /// <param name="lst">Checked string list</param>
        /// <returns>True if existed. Otherwise, False</returns>
        private Boolean IsExistInList(String strChecked, List<String> lstDetail)
        {
            foreach (String str in lstDetail)
            {
                if (str.Equals(strChecked)) // checked string existed in list
                {
                    return true;
                }
            }

            return false;
        }

        #endregion
        //---------------------------------------------------------------------
        //-------------------------------------Show List Directorate-----------
        #region BU/Directorate
        protected void chkInActive_CheckedChanged(object sender, EventArgs e)
        {
            Session["includeInactive"] = chkInActive.Checked;
            LoadData(Session["fString"].ToString(), chkInActive.Checked);
        }
        /// <summary>
        /// Get all list organization
        /// </summary>
        private void LoadData(String filterString, Boolean includeInactive)
        {
            if (filterString.Equals("")) // show all organization
            {

                IDirectorateBIZ drectBIZ = new DirectorateBIZ();
                DataTable dt = drectBIZ.GetAllFilter(includeInactive);
                BindData(dt);
            }
            else
            {
                IDirectorateBIZ drectBIZ = new DirectorateBIZ();
                DataTable dt = drectBIZ.GetAll(filterString, includeInactive);
                BindData(dt);
            }
            Session["fString"] = filterString;
        }
        /// <summary>
        /// Bind data to datagrid
        /// </summary>
        /// <param name="dtbDataSource"></param>
        private void BindData(DataTable dtbDataSource)
        {
            // If have data in table
            if (dtbDataSource.Rows.Count > 0)
            {
                gvOrganizationList.DataSource = dtbDataSource;
                gvOrganizationList.DataBind();
                lblMessage.Text = string.Empty;
            }
            else // if have no data in table
            {
                dtbDataSource.Rows.Add(dtbDataSource.NewRow());
                gvOrganizationList.DataSource = dtbDataSource;
                gvOrganizationList.DataBind();
                gvOrganizationList.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
            }
        }
        private SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sortExpression"></param>
        /// <param name="direction"></param>
        private void SortGridView(string sortExpression, string direction)
        {
            IDirectorateBIZ drectBIZ = new DirectorateBIZ();
            DataTable tb = new DataTable();

            // List all organization
            if (Session["fString"].Equals(""))
            {
                tb = drectBIZ.GetAllFilter(Convert.ToBoolean(Session["includeInactive"]));
            }
            // List organization is up to remain filter
            else
            {
                tb = drectBIZ.GetAll(Session["fString"].ToString(), Convert.ToBoolean(Session["includeInactive"]));
            }
            if (tb.Rows.Count > 0)
            {
                DataView dv = new DataView(tb);
                dv.Sort = sortExpression + direction;
                gvOrganizationList.DataSource = dv;
                gvOrganizationList.DataBind();
            }
            else
            {
                tb.Rows.Add(tb.NewRow());
                gvOrganizationList.DataSource = tb;
                gvOrganizationList.DataBind();
                gvOrganizationList.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
            }

        }

        /// <summary>
        /// Filter: all organization that begin with the letter in '0 - 9'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbn09_Click(object sender, EventArgs e)
        {
            LoadData("[0-9]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'A B C D E'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnABCDE_Click(object sender, EventArgs e)
        {
            LoadData("[A-E]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'F G H I J'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnFGHIJ_Click(object sender, EventArgs e)
        {
            LoadData("[F-J]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'K L M N'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnKLMN_Click(object sender, EventArgs e)
        {
            LoadData("[K-N]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'O P Q R'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnOPQR_Click(object sender, EventArgs e)
        {
            LoadData("[O-R]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'S T U V'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSTUV_Click(object sender, EventArgs e)
        {
            LoadData("[S-V]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        /// <summary>
        /// Filter: all organization that begin with the letter in 'W X Y Z'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnWXYZ_Click(object sender, EventArgs e)
        {
            LoadData("[W-Z]%", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }
        protected void btnCreateDirectory_Click(object sender, EventArgs e)
        {
             Response.Redirect("UpdateDirectorate.aspx");
        }
        protected void lbnAll_Click(object sender, EventArgs e)
        {
            LoadData("", Convert.ToBoolean(Session["includeInactive"].ToString()));
        }

        protected void gvOrganizationList_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            ViewState["SortExpression"] = sortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            }
        }

        protected void gvOrganizationList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOrganizationList.PageIndex = e.NewPageIndex;
            LoadData(Session["fString"].ToString(), Convert.ToBoolean(Session["includeInactive"].ToString()));
        }
        #endregion

        //---------------------------------------------------------------------
        //-----------------------------Show Detail5----------------------------

        #region Detail5
        private void ShowDetail5()
        {
            PopulateSupportingMaterialsGrid();
        }

        protected static int currentPageNumber = 1;
        protected const int pageSize = 15;
        protected static int totalPages = 0;


        private DataTable GetSupportingMaterialsData()
        {
            ISupportingMaterialBIZ smBIZ = new SupportingMaterialBIZ();
            string orgId = Request.QueryString["orgId"];

            try
            {
                List<SupportingMaterial> list = smBIZ.SelectByOrgId(orgId, currentPageNumber, pageSize, out totalPages, CheckBox1.Checked);

                DataTable dt = new DataTable();
                dt.Columns.Add("SupportingMaterialID");
                dt.Columns.Add("URL");
                dt.Columns.Add("Description");
                dt.Columns.Add("Type");
                //dt.Columns.Add("AddedBy");
                dt.Columns.Add("AddedDate");
                dt.Columns.Add("IsActive");

                if (list.Count > 0)
                {
                    foreach (SupportingMaterial item in list)
                    {
                        DataRow row = dt.NewRow();
                        row["SupportingMaterialID"] = item.SupportingMaterialId;
                        row["URL"] = item.URL;
                        row["Description"] = item.Description;
                        row["Type"] = item.Type.RefValue;
                        //row["AddedBy"] = item.AddedBy.Account;
                        row["AddedDate"] = item.AddedDate.ToString();
                        row["IsActive"] = item.IsActive.ToString();

                        dt.Rows.Add(row);
                    }
                }

                return dt;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        private void PopulateSupportingMaterialsGrid()
        {
            DataTable dt = GetSupportingMaterialsData();

            if (dt.Rows.Count > 0)
            {
                gvSupportingMaterial.DataSource = dt;
                gvSupportingMaterial.DataBind();
                lblMessage.Text = string.Empty;

                lblTotalPages.Text = totalPages.ToString();
                lblCurrentPage.Text = currentPageNumber.ToString();

                if (currentPageNumber == 1)
                {
                    btnPrevious.Enabled = false;

                    if (totalPages > 0)
                    {
                        btnNext.Enabled = true;
                    }
                    else
                    {
                        btnNext.Enabled = false;
                    }

                }
                else
                {
                    btnPrevious.Enabled = true;

                    if (currentPageNumber == totalPages)
                    {
                        btnNext.Enabled = false;
                    }
                    else
                    {
                        btnNext.Enabled = true;
                    }
                }
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                gvSupportingMaterial.DataSource = dt;
                gvSupportingMaterial.DataBind();
                gvSupportingMaterial.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
                lblTotalPages.Text = "0";
                lblCurrentPage.Text = "0";
                btnFirst.Enabled = false;
                btnPrevious.Enabled = false;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
        }

        // This method will handle the navigation/ paging index
        protected void ChangePage(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "First":
                    currentPageNumber = 1;
                    break;

                case "Previous":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1;
                    break;

                case "Next":
                    currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1;
                    break;

                case "Last":
                    currentPageNumber = totalPages;
                    break;
            }

            PopulateSupportingMaterialsGrid();
        }

        public SortDirection gvSupportingMaterialSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Descending;

                return (SortDirection)ViewState["sortDirection"];
            }
            set
            {
                ViewState["sortDirection"] = value;
            }
        }

        protected void gvSupportingMaterial_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;

            if (gvSupportingMaterialSortDirection == SortDirection.Ascending)
            {
                gvSupportingMaterialSortDirection = SortDirection.Descending;
                SMSortGridView(sortExpression, DESCENDING);
            }
            else
            {
                gvSupportingMaterialSortDirection = SortDirection.Ascending;
                SMSortGridView(sortExpression, ASCENDING);
            }
        }

        private void SMSortGridView(string sortExpression, string direction)
        {
            DataTable dt = GetSupportingMaterialsData();

            if (dt.Rows.Count > 0)
            {
                DataView dv = new DataView(dt);
                dv.Sort = sortExpression + direction;

                gvSupportingMaterial.DataSource = dv;
                gvSupportingMaterial.DataBind();
                lblMessage.Text = string.Empty;

                lblTotalPages.Text = totalPages.ToString();
                lblCurrentPage.Text = currentPageNumber.ToString();

                if (currentPageNumber == 1)
                {
                    btnPrevious.Enabled = false;

                    if (totalPages > 0)
                    {
                        btnNext.Enabled = true;
                    }
                    else
                    {
                        btnNext.Enabled = false;
                    }

                }
                else
                {
                    btnPrevious.Enabled = true;

                    if (currentPageNumber == totalPages)
                    {
                        btnNext.Enabled = false;
                    }
                    else
                    {
                        btnNext.Enabled = true;
                    }
                }
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                gvSupportingMaterial.DataSource = dt;
                gvSupportingMaterial.DataBind();
                gvSupportingMaterial.Rows[0].Visible = false;
                lblMessage.Text = "No records found";
                lblTotalPages.Text = "0";
                lblCurrentPage.Text = "0";
                btnFirst.Enabled = false;
                btnPrevious.Enabled = false;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }


        }

        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            PopulateSupportingMaterialsGrid();
        }

        #endregion

    }
}
